package com.davidjr621.rebooter;

import java.io.DataOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

	private static final String TAG = "Hot Reboot - ";
	public static String TITLE_FONT = "BD_Bankwell.ttf";
	private int HOTREBOOT = 0;
	private int REBOOT = 1;
	private int POWERDOWN = 2;
	private int RECOVERY = 3;
	private static String rebootCmd;
	private static boolean showPopups;
	private static String dialogMsg;
	private static SharedPreferences preferences;
	private ProgressDialog pbarDialog;
	protected String toastMsg;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		preferences = PreferenceManager.getDefaultSharedPreferences(this);
		super.onCreate(savedInstanceState);
		handler.sendEmptyMessage(0);
	}

	public void OnClickListen() {
		Button button =(Button)findViewById(R.id.hotreboot);
		Button button2 =(Button)findViewById(R.id.reboot);
		Button button3 =(Button)findViewById(R.id.powerdown);
		Button button4 =(Button)findViewById(R.id.recovery);
		button.setOnClickListener(this);
		button2.setOnClickListener(this);
		button3.setOnClickListener(this);
		button4.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "Exit").setIcon(android.R.drawable.ic_menu_close_clear_cancel);
		return true;
	}

	/* Handles item selections */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			finish();
			return true;
		}
		return(super.onOptionsItemSelected(item));
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		if (id == HOTREBOOT) {
			return (new AlertDialog.Builder(this))
			.setCancelable(true)
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setTitle("Hot Reboot")
			.setMessage("Click for a hot reboot.")
			.setPositiveButton("Reboot", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					removeDialog(HOTREBOOT);					
					doReboot();					
					Log.d(TAG , "hot rebooting");
				}
			})
			.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					removeDialog(HOTREBOOT);
				}
			})
			.create();
		} else if (id == REBOOT) {
			return (new AlertDialog.Builder(this))
			.setCancelable(true)
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setTitle("Reboot")
			.setMessage("Click for a reboot.")
			.setPositiveButton("Reboot", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					removeDialog(REBOOT);						
					doReboot();					
					Log.d(TAG , "rebooting");
				}
			})
			.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					removeDialog(REBOOT);
				}
			})
			.create();
		} else if (id == POWERDOWN) {
			return (new AlertDialog.Builder(this))
			.setCancelable(true)
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setTitle("Powerdown")
			.setMessage("Click to shutdown your device.")
			.setPositiveButton("Power Off", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					removeDialog(POWERDOWN);
					doReboot();					
					Log.d(TAG , "powering down");
				}
			})
			.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					removeDialog(POWERDOWN);
				}
			})
			.create();
		} else if (id == RECOVERY) {
			return (new AlertDialog.Builder(this))
			.setCancelable(true)
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setTitle("Reboot Recovery")
			.setMessage("Click to reboot into recovery mode.")
			.setPositiveButton("Recovery", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					removeDialog(RECOVERY);
					doReboot();					
					Log.d(TAG , "rebooting into recovery");
				}
			})
			.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					removeDialog(RECOVERY);
				}
			})
			.create();
		}
		return null;
	}

	public void doReboot() {

		handler.postDelayed(new Runnable() { 
			public void run() { } 
		}, 1000);

		toastMsg = "";
		pbarDialog = new ProgressDialog(MainActivity.this);
		pbarDialog.setMessage(dialogMsg);

		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
		pbarDialog.show();

		Thread fixThread = new Thread(){
			@Override
			public void run() {
				Looper.prepare();
				final Runtime run = Runtime.getRuntime();
				DataOutputStream out = null;
				Process p = null;
				try {
					p = run.exec("su");
					out = new DataOutputStream(p.getOutputStream());
					out.writeBytes(rebootCmd + "\n");
					out.flush();
					toastMsg = dialogMsg;
				} catch (IOException e) {
					Log.e(TAG, "Fail :( ", e);
					e.printStackTrace();
					toastMsg = "Something went wrong!";
					handler.sendEmptyMessage(1);
					return;
				}
				handler.sendEmptyMessage(1);
			}
		};
		fixThread.start();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case 0:
				setContentView(R.layout.main);
				
				TextView Title =(TextView)findViewById(R.id.titleText);
				Title.setText("Rebooter");
				Typeface TitleFont = Typeface.createFromAsset(getAssets(),TITLE_FONT);
				Title.setTypeface(TitleFont);
				
				OnClickListen();
				
				CheckBox cb = (CheckBox)findViewById(R.id.showPopups);

				showPopups = (preferences.getBoolean("showPopups_enabled", true));
				cb.setChecked(showPopups);

				cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
					public void onCheckedChanged(CompoundButton buttonView,	boolean isChecked) {
						showPopups = isChecked;
						SharedPreferences.Editor editor = preferences.edit();
						editor.putBoolean("showPopups_enabled", isChecked);
						editor.commit();
					}
				});		
				
				break;
			case 1:
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
				pbarDialog.dismiss();				
				Toast.makeText(getApplicationContext(),toastMsg, Toast.LENGTH_LONG).show();
				break;
			}
			return;
		}
	};

	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.hotreboot:
			dialogMsg = "Rebooting ...";
			rebootCmd = "busybox killall system_server";
			if (showPopups) {showDialog(HOTREBOOT);} else {doReboot();}
			break;
		case R.id.reboot:
			dialogMsg = "Rebooting ...";
			rebootCmd = "reboot";
			if (showPopups) {showDialog(REBOOT);} else {doReboot();}
			break;
		case R.id.powerdown:
			dialogMsg = "Shutting down ...";
			rebootCmd = "reboot -p";
			if (showPopups) {showDialog(POWERDOWN);} else {doReboot();}
			break;
		case R.id.recovery:
			dialogMsg = "Rebooting to recovery ...";
			rebootCmd = "reboot recovery";
			if (showPopups) {showDialog(RECOVERY);} else {doReboot();}
			break;
		}

	}
}